import Axios from 'axios'
import Qs from 'qs'
import store from '../vuex'
import router from '../router'
import * as config from '../utils/config'
// import global from '../utils/global'

function install (Vue) {
  // Axios.defaults.baseURL = config.BASE_URL + '/client'
  Axios.defaults.baseURL = (process.env.NODE_ENV !== 'production' ? '/api' : '') + '/client'
  Axios.defaults.headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'clientId': 5
  }
  Axios.defaults.timeout = 60000
  Axios.interceptors.request.use((request) => {
    if (!request.data) {
      request.data = {}
    }
    // request.method = 'POST'
    // 公共的请求头参数
    // request.headers.webId = global.webId // 网站序号
    // request.headers.clientSecrect = global.clientSecrect // 密钥
    // request.headers.webHost = global.host // 域名
    if (request.url.toUpperCase().indexOf('UPLOAD') < 0) {
      store.dispatch('openLoading')
      // 如果post的data 为 null 就赋值为一个对象
      if (!request.data) {
        request.data = {}
      }
      // 再转换成数据库的格式 发送
      // 遍历参数 如果有 undefined 的就删除这个参数
      for (let params in request.data) {
        if (request.data[params] === undefined || request.data[params] === '' || request.data[params] === null) {
          delete request.data[params]
        }
      }
      // 登录校验
      if (store.getters.userInfo && store.getters.userInfo.token) {
        request.headers.token = store.getters.userInfo.token
      }
      // request.headers.userId = 13
      // 删除get参数 上一步已经合并为POST数据了 不需要重复的数据传输
      delete request.params
      if (!request.data.isJson) {
        for (let params in request.data) {
          if (typeof request.data[params] === 'object') {
            delete request.data[params]
          }
        }
        request.data = Qs.stringify(request.data)
      } else {
        request.headers['Content-Type'] = 'application/json'
      }
    }
    return request
  }, (error) => {
    console.log("error: ", error)
  })
  // Add a response interceptor
  Axios.interceptors.response.use((response) => {
    store.dispatch('closeLoading')
    
    switch (response.data.code) {
      case 0:
        return  new Promise((resolve, reject) => {
          resolve(response.data);
        });
      case 444:
        store.dispatch('logout')
        // 暂时微信订阅号不能进行用户信息授权,所以我们现在关联一个微信服务号
        // if (process.env.NODE_ENV === 'production' && /micromessenger/.test(window.navigator.userAgent.toLowerCase())) {
        //   window.location.href = '/client/wechat/mpAuthorize?returnUrl=' + encodeURIComponent(window.location.href)
        // }
        // return Promise.reject(response.data)
        // 没有登录
        router.replace({name: 'Login', params: {backUrl: window.location.href}})
        break
      default:
        // store.dispatch('showToast', {text: response.data.msg})
        return new Promise((resolve, reject) => {
          resolve(response.data);
        });
    }
  }, (error) => {
    // Do something with response error
    store.dispatch('closeLoading')
    console.log("error1: ", error)
    if (JSON.stringify(error).indexOf('404') > 0) {
      console.log('系统错误')
    } else {
      console.log('网络错误')
    }
    return Promise.reject(error)
  })
  Vue.prototype.$http = Axios
  Vue.prototype.axios = Axios
}

export default install
